package com.xin.core
{
	import com.xin.utils.GarbageClean;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * 所有显示对象的基类, 专门处理垃圾回收并提供添加事件和自动删除事件机制.
	 * @author daichangxin
	 * 
	 */	
	public class DisposeBase extends Sprite
	{
		private var _listenerList:Array = [];
		
		public function DisposeBase()
		{
			super.addEventListener(Event.REMOVED_FROM_STAGE, removeFromStageHandler);
		}
		/**
		 * 从舞台上移出处理函数
		 * 删除所有侦听并执行dispose释放内存
		 */
		private function removeFromStageHandler(evt:Event):void
		{
			super.removeEventListener(Event.REMOVED_FROM_STAGE, removeFromStageHandler);
			trace("removeFromStageHandler执行");
			for (var i:int = 0; i < _listenerList.length; i++)
			{
				var itemListener:Object = _listenerList[i];
				var obj:DisplayObject = itemListener["target"];
				var type:String = itemListener["type"];
				var handler:Function = itemListener["handler"];
				if (obj && type && (handler != null))
				{
					trace("removeFromStageHandler中的删除侦听: ___type: ", type, "__target: ", obj);
					obj.removeEventListener(type, handler);
				}
			}
			var g:GarbageClean = new GarbageClean();
			g.gc();
		}

		/**
		 * 给显示对象添加事件函数
		 * @param target 对象
		 * @param type 事件类型
		 * @param handler 事件处理函数
		 */		
		public function addListener(target:DisplayObject, type:String, handler:Function):void
		{
			if (target)
			{
				target.addEventListener(type, handler);
				_listenerList.push({"target":target, "type":type, "handler":handler});
				trace("super.addListener: __ type: ", type, "__target: ", target);
			}
		}
		/**
		 * 删除显示对象的侦听
		 * @param target
		 * @param type
		 * @param handler
		 * 
		 */		
		public function removeListener(target:DisplayObject, type:String, handler:Function):void
		{
			if (target)
			{
				target.removeEventListener(type, handler);
				trace("super.removeListener: __ type: ", type, "__target: ", target);
				for (var i:int = 0; i < _listenerList.length; i++)
				{
					var itemObj:Object = _listenerList[i];
					if ((itemObj["target"] == target) && (itemObj["type"] == type))
					{
						_listenerList.splice(i, 1);
					}
				}
			}
		}
		
		/**
		 * 获取显示对象的所有侦听事件
		 * 每一条数据格式为: {"target":target, "type":type, "handler":handler}
		 */		
		public function get listenerList():Array
		{
			return _listenerList;
		}
	}
}